<!-- user management -->
<script setup lang="ts">
import { reactive, ref, toRefs, onMounted } from 'vue';
import { ElPagination, ElMessageBox, ElMessage } from "element-plus";
import { Page } from '@vben/common-ui';
import { Query, EditDialog, OrgList, BatchUploadOrgDialog } from './modules/studentMgr';
import { Trash2 } from '@vben/icons';
import ResizableLayout from '#/components/common/resizable-layout.vue'
import dayjs from 'dayjs';
import { $t } from '#/locales/index.js';
import { trimStringParams } from '#/utils/trimStringParams';
import { getStuListApi, deleteStuApi, getOrgExamStatusApi } from '#/api/certificate/studentMgr';


defineOptions({ name: 'StudentMgr' })

const editDialogRef = ref<InstanceType<typeof EditDialog> | null>(null);
const batchUploadOrgDialogRef = ref<InstanceType<typeof BatchUploadOrgDialog> | null>(null);
const orgExamStatus = ref(false)
const tableData = ref([])
const total = ref(0)
const tableLoading = ref(false)
const selectList = ref([])
const currentOrgId = ref('')

const pageData = ref({
  curPage: 1,
  pageSize: 10
})

const defaultQueryData = {
  phone: '',
  name: '',
  createTime: null,
}

const queryData = ref({ ...defaultQueryData })

const getTableData = () => {
  const params = {
    id: currentOrgId.value,
    curPage: pageData.value.curPage,
    pageSize: pageData.value.pageSize,
  } as any;
  const trimData = trimStringParams({...queryData.value})
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal && key !== 'createTime') {
      params[key] = kVal
    } else if (key === 'createTime' && Array.isArray(kVal)) {
      params['startTime'] = kVal[0]
      params['endTime'] = kVal[1]
    }
  })
  tableLoading.value = true
  getStuListApi(params)
    .then((res) => {
      const { data, pageInfo } = res;
      tableData.value = data;
      total.value = pageInfo?.totalRows
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

const handleSizeChange = (val: number) => {
  pageData.value.pageSize = val
  pageData.value.curPage = 1
  getTableData()
}

const handleCurrentChange = (val: number) => {
  pageData.value.curPage = val
  getTableData()
}

const resetQuery = () => {
  Object.assign(queryData.value, defaultQueryData)
  getTableData()
}

const deleteStu = (data: any) => {
  if (orgExamStatus.value) {
    ElMessage.warning($t('studentMgr.orgExamStatusTxt'))
    return
  }
  ElMessageBox.confirm(
    $t('common.submitTxt', [$t('common.deleteTxt', [$t('studentMgr.studentTxt')])]),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      deleteStuApi(data.id).then(() => {
        ElMessage.success($t('common.deleteTxt', [$t('common.successTxt')]))
        getTableData()
      }).finally(() => {
      })
    })
    .catch(() => { })
}

const handleSelectionChange = (data: any) => {
  selectList.value = data
}

const onAdd = () => {
  if (orgExamStatus.value) {
    ElMessage.warning($t('studentMgr.orgExamStatusTxt'))
    return
  }
  editDialogRef.value?.inint(null);
};

const batchAdd = () => {
  batchUploadOrgDialogRef.value?.inint()
}

const getOrgExamStatus = (id: any) => {
  getOrgExamStatusApi(id).then((res: any) => {
    if (!res) {
      orgExamStatus.value = false
      return
    }
    const { status } = res
    orgExamStatus.value = status !== 'new' && status !== 'published'
  }).finally(() => {
  })
}

const queryStuData = (id: any) => {
  console.log(id)
  currentOrgId.value = id
  getTableData()
  getOrgExamStatus(id)
}

const handleResize = (width: number) => {
  console.log('左侧面板宽度调整为:', width)
}

onMounted(() => {
  // getTableData();
})
</script>

<template>
  <Page class="h-full">
    <section class="h-full bg-[#fff] rounded-sm">
      <ResizableLayout 
        :default-width="200"
        :min-width="180"
        :max-width="500"
        :handle-width="1"
        :handle-color="'#DCDFE6'"
        @resize="handleResize"
      >
        <template #left>
          <div class="h-full pr-[15px] pt-[24px] pl-[24px] pb-[24px]">
            <OrgList @queryStuData="queryStuData"></OrgList>
          </div>
        </template>
        
        <template #right>
          <div class="h-full flex flex-col p-[24px] pl-[16px]">
            <Query v-model="queryData" class="mb-[5px]" @query-data="getTableData" @reset-query="resetQuery" />
            <div class="mb-[15px]">
              <el-button  type="primary" @click="onAdd">{{ $t('common.newTxt') }}</el-button>
              <!-- <el-button @click="batchAdd">{{ $t('common.batchNewTxt') }}</el-button> -->
            </div>
            <el-table @selection-change="handleSelectionChange" :data="tableData" class="flex-1 overflow-auto"
              v-loading="tableLoading">
              <el-table-column header-align="center" align="center" width="60" type="selection"></el-table-column>
              <el-table-column align="center" width="60px" type="index" :label="$t('common.numberIdxTxt')" />
              <el-table-column prop="nameCn" :label="$t('studentMgr.nameTxt')" min-width="80">
                <template #default="{ row }">
                  <div>{{ row.nameCn || '--' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="phone" :label="$t('common.phoneTxt')" min-width="116" />

              <el-table-column :label="$t('studentMgr.affiliatedOrgTxt')" prop="orgName" min-width="120px">
              </el-table-column>
              <el-table-column prop="createTime" :label="$t('common.createTimeTxt')" min-width="110px">
                <template #default="{ row }">
                  <div>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('common.handleTxt')" min-width="60">
                <template #default="{ row }">
                  <el-tooltip effect="dark" :content="$t('common.deleteTxt')" :show-after="1000" placement="top">
                    <el-button :icon="Trash2" link @click="deleteStu(row)"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <ElPagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
              size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
              :page-size="pageData.pageSize" :total="total"></ElPagination>
          </div>
        </template>
      </ResizableLayout>
      
      <EditDialog ref="editDialogRef" :currentOrgId="currentOrgId" @query-table="getTableData" />
      <BatchUploadOrgDialog ref="batchUploadOrgDialogRef" />
    </section>
  </Page>
</template>

<style scoped>
.resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 1px;
  background: #e0e0e0;
  cursor: col-resize;
  z-index: 10;
  transition: background-color 0.2s;
}

.resize-handle:hover {
  background: #c0c0c0;
}

.resize-handle:active {
  background: #a0a0a0;
}

/* 拖拽时禁用文本选择 */
.left-part {
  user-select: none;
}

/* 拖拽时显示拖拽光标 */
.left-part:has(.resize-handle:hover) {
  cursor: col-resize;
}
</style>
